<template>
	<!-- 整体容器 -->
	<view class="page-container">

		<!-- 1. 总资产模块 -->
		<view class="total-assets-card">
			<view class="total-assets-header">
				<text class="total-assets-label">总资产（元）</text>
				<text class="total-assets-value">{{ totalAssets }}</text>
			</view>
			<view class="total-assets-footer">
				<text class="income-item">昨日收益+{{ yesterdayIncome }}</text>
				<text class="income-item">累计收益+{{ totalIncome }}</text>
			</view>
			<button class="withdraw-btn" @click="handleWithdraw">提现 &gt;</button>
		</view>

		<!-- 2. 操作入口（资金明细、佣金比例） -->
		<view class="operation-bar">
			<view class="operation-item" :class="{ active: currentTab === 'fund' }" @click="switchTab('fund')">
				<image class="operation-icon" src="/static/image/zijinmingxi.png" mode="widthFix"></image>
				<text class="operation-text">资金明细</text>
			</view>
			<view class="operation-item" :class="{ active: currentTab === 'commission' }"
				@click="switchTab('commission')">
				<image class="operation-icon" src="/static/image/yongjinbili.png" mode="widthFix"></image>
				<text class="operation-text">佣金比例</text>
			</view>
		</view>

		<!-- 3. 充值模块 -->
		<view class="recharge-section">
			<!-- 充值金额输入 -->
			<view class="recharge-amount-box">
				<text class="recharge-label">充值金额</text>
				<input class="recharge-input" placeholder="请输入充值金额" v-model="rechargeAmount" />
			</view>

			<!-- 快捷充值 -->
			<view class="quick-recharge-box">
				<text class="quick-recharge-label">快捷充值</text>
				<view class="quick-amount-list">
					<view class="quick-amount-item" :class="{ active: selectedQuickAmount === item.amount }"
						v-for="(item, index) in quickAmountList" :key="index" @click="selectQuickAmount(item.amount)">
						<text class="amount-value">¥{{ item.amount }}</text>
						<text class="original-price">原价¥{{ item.originalPrice }}</text>
					</view>
				</view>
			</view>

			<!-- 协议与按钮 -->
			<view class="agreement-box">
				<checkbox-group @change="handleAgreementChange">
					<checkbox class="agreement-checkbox" :value="true" :checked="agreementChecked"></checkbox>
				</checkbox-group>
				<text class="agreement-text">
					我已阅读并同意
					<text class="policy-link-text" @click="showRechargePolicy">《充值服务协议》</text>
				</text>
			</view>
			<button class="confirm-recharge-btn" @click="handleRecharge">立即充值</button>

		</view>

		<!-- 充值协议弹窗 -->
		<view class="recharge-policy-popup" v-if="isPolicyPopupVisible">
			<view class="popup-mask" @click="closePolicyPopup"></view>
			<view class="popup-content">
				<view class="popup-header">
					<text class="popup-title">充值服务协议</text>
					<text class="close-btn" @click="closePolicyPopup">×</text>
				</view>
				<view class="policy-content">
					<text class="policy-title">一、充值说明</text>
					<text class="policy-paragraph">
						1. 充值金额将直接存入您的账户余额，可用于平台内消费。
					</text>
					<text class="policy-paragraph">
						2. 充值成功后，资金将实时到账，如遇网络延迟请稍后查询。
					</text>
					<text class="policy-title">二、退款规则</text>
					<text class="policy-paragraph">
						1. 虚拟商品充值成功后，除法律规定情形外，不支持退款。
					</text>
					<text class="policy-paragraph">
						2. 如遇充值未到账情况，请联系客服处理。
					</text>
					<text class="policy-title">三、注意事项</text>
					<text class="policy-paragraph">
						1. 请通过官方渠道充值，避免使用非授权途径造成损失。
					</text>
					<text class="policy-paragraph">
						2. 请妥善保管账户信息，因个人原因导致的损失由用户自行承担。
					</text>
				</view>
				<view class="popup-footer">
					<button class="reject-btn" @click="closePolicyPopup">不同意</button>
					<button class="accept-btn" @click="acceptPolicy">同意并继续</button>
				</view>
			</view>
		</view>
	</view>
</template>

<script setup>
	import {
		ref,
		onMounted,
		onUnmounted,
		nextTick,
		watch
	} from 'vue';

	import {
		onLoad,
		onShow
	} from '@dcloudio/uni-app';
	// 假设你的接口文件路径正确，若有调整需对应修改
	import {
		getShouYi
	} from '@/api/xiaoquan.js';

	import {
		addOrderChongZhiInfo,
		createChongZhiOrder,
		updateChongZhiOrderStatus
	} from "@/api/xiaoquan.js";

	// 响应式数据
	const totalAssets = ref('0.00'); // 总资产
	const yesterdayIncome = ref('0'); // 昨日收益
	const totalIncome = ref('25.32'); // 累计收益
	const currentTab = ref('fund'); // 当前选中的操作入口（fund/commission）
	const rechargeAmount = ref(''); // 自定义充值金额
	const selectedQuickAmount = ref(null); // 选中的快捷充值金额
	// 用于维护协议是否勾选
	const agreementChecked = ref(false);
	const quickAmountList = ref([ // 快捷充值配置
		{
			amount: 90,
			originalPrice: 100
		},
		{
			amount: 180,
			originalPrice: 200
		},
		{
			amount: 270,
			originalPrice: 300
		}
	]);

	// 充值协议相关状态
	const isPolicyPopupVisible = ref(false); // 充值协议弹窗是否显示

	// 图标地址（根据实际路径替换，若有静态资源需放置对应位置）
	const fundIcon = ref('/static/icon/fund.png');
	const commissionIcon = ref('/static/icon/commission.png');

	// 页面加载时获取资产数据
	onShow(async () => {
		try {
			getShouYi().then((res) => {
				// totalAssets获取总资产
				totalAssets.value = res.data.zongZiChan || '0.00'
				totalIncome.value = res.data.zongMonery || '0.00';
				// 这里假设接口返回昨日收益，若没有可保持默认值
				yesterdayIncome.value = res.data.yesterdayIncome || '0';
			});
		} catch (error) {
			console.error('获取资产信息失败:', error);
		}
	});

	// 切换操作入口（资金明细、佣金比例）
	const switchTab = (tab) => {
		currentTab.value = tab;
		// 可在此处根据 tab 切换不同的列表 / 接口逻辑， 比如：
		if (tab === 'fund') {
			// 调用资金明细接口
			// 跳转到资金明细页面
			uni.navigateTo({
				url: "/package/pages/zijinliushui/zijinliushui"
			})
		} else if (tab === 'commission') {
			// 调用佣金比例接口
			uni.navigateTo({
				url: "/package/pages/yong_jin_bi_li/yong_jin_bi_li"
			})
		}
	};

	// 选择快捷充值金额
	const selectQuickAmount = (amount) => {
		selectedQuickAmount.value = amount;
		rechargeAmount.value = amount.toString(); // 同步到输入框
	};

	// 提现逻辑（示例，需结合实际接口完善）
	const handleWithdraw = () => {
		uni.navigateTo({
			url: '/package/pages/dpCertificationDetail/dpCertificationDetail'
		});
	};

	// 处理协议勾选变化事件
	const handleAgreementChange = (e) => {
		agreementChecked.value = e.detail.value.length > 0;
	};

	// 显示充值协议弹窗
	const showRechargePolicy = () => {
		isPolicyPopupVisible.value = true;
	};

	// 关闭充值协议弹窗
	const closePolicyPopup = () => {
		isPolicyPopupVisible.value = false;
	};

	// 接受充值协议并执行充值
	const acceptPolicy = () => {
		isPolicyPopupVisible.value = false;
		agreementChecked.value = true; // 勾选协议
		// handleRechargeProcess(); // 执行充值流程
	};

	// 充值成功调用方法
	const chongZhiAwait = async (data) => {
		await updateChongZhiOrderStatus(data)
		getShouYi().then((res) => {
			// totalAssets获取总资产
			totalAssets.value = res.data.zongZiChan || '0.00'
			totalIncome.value = res.data.zongMonery || '0.00';
			// 这里假设接口返回昨日收益，若没有可保持默认值
			yesterdayIncome.value = res.data.yesterdayIncome || '0';
		});
	};

	// 充值逻辑（示例，需结合实际支付接口完善）
	const handleRecharge = () => {
		// 检查是否输入充值金额
		if (!rechargeAmount.value) {
			uni.showToast({
				title: '请输入充值金额',
				icon: 'none'
			});
			return;
		}

		// 检查是否勾选协议
		if (!agreementChecked.value) {
			uni.showToast({
				title: '请先阅读并同意充值服务协议',
				icon: 'none'
			});
			showRechargePolicy(); // 显示协议弹窗
			return;
		}

		// 执行充值流程
		handleRechargeProcess();
	};

	const handleRechargeProcess = async () => {
		try {
			// 创建订单
			let data1 = {
				amount: rechargeAmount.value
			}

			let res = await addOrderChongZhiInfo(data1);

			if (res.code == 200) {
				let payData = {
					orderNo: res.data
				}
				let payres = await createChongZhiOrder(payData);
				console.log(payres, 123)
				if (payres.code == 200) {
					wx.requestPayment({
						timeStamp: payres.data.jsConfig.timeStamp,
						nonceStr: payres.data.jsConfig.nonceStr,
						package: payres.data.jsConfig.packageVal,
						paySign: payres.data.jsConfig.paySign,
						signType: payres.data.jsConfig.signType, // 该参数为固定值
						success(res) {
							uni.showToast({
								title: '支付成功',
								icon: 'none'
							})
							// 根据订单状态修改订单状态 修改成为已支付
							let data = {
								orderId: payData.orderNo,
								status: 1
							}
							console.log(data, "111111111111112222222222222============")
							chongZhiAwait(data);
						},
						fail(err) {
							// 支付失败回调
							console.error('唤起支付组件失败：', err);
							uni.showToast({
								title: '支付失败',
								icon: 'none'
							})
							//根据订单状态修改订单状态 修改成为已取消
							let data = {
								orderNo: orderParams.orderNo,
								status: 3
							}
							updateChongZhiOrderStatus(JSON.stringify(data))
						}
					});
				}
			}
		} catch (error) {
			console.error('微信支付处理异常:', error);
			uni.showToast({
				title: '支付处理失败，请重试',
				icon: 'none'
			});
		}
	};
</script>

<style scoped>
	/* 页面整体 */
	.page-container {
		padding: 20rpx;
		background-color: #fff;
		position: relative;
	}

	/* 总资产卡片 */
	.total-assets-card {
		background: linear-gradient(to right, #4284ff, #545ce9);
		border-radius: 20rpx;
		padding: 30rpx;
		color: #fff;
		margin-bottom: 20rpx;
		position: relative;
		height: 200rpx;
	}

	.total-assets-header {
		display: grid;
	}

	.total-assets-label {
		font-size: 28rpx;
		opacity: 0.9;
		margin: 10px 0;
	}

	.total-assets-value {
		font-size: 48rpx;
		font-weight: bold;
	}

	.total-assets-footer {
		display: flex;
		justify-content: start;
		margin: 19rpx 0;
	}

	.income-item {
		font-size: 24rpx;
		opacity: 0.9;
		margin: 5px;
	}

	.withdraw-btn {
		margin-top: 20rpx;
		background: linear-gradient(to right, #599af3, #545ce9);
		color: #fff;
		border-radius: 50px;
		font-size: 26rpx;
		position: absolute;
		right: 0;
		top: 78rpx;
		width: 183rpx;
		box-shadow: -8px 0px 4px #4058cd;
	}

	/* 操作入口（资金明细、佣金比例） */
	.operation-bar {
		display: flex;
		justify-content: space-around;
		margin-bottom: 30rpx;
	}

	.operation-item {
		display: flex;
		flex-direction: column;
		align-items: center;
		width: 45%;
	}

	.operation-icon {
		width: 60rpx;
		height: 60rpx;
	}

	.operation-text {
		margin-top: 10rpx;
		font-size: 26rpx;
		color: #666;
	}

	.operation-item.active {
		color: #4b8df8;
	}

	/* 充值模块 */
	.recharge-section {
		background-color: #fbfbfb;
		border-radius: 20rpx;
		padding: 20rpx;
	}

	.recharge-amount-box {
		margin-bottom: 30rpx;
	}

	.recharge-label {
		font-size: 30rpx;
		color: #333;
		display: block;
		margin-bottom: 10rpx;
	}

	.recharge-input {
		width: 100%;
		height: 60rpx;
		line-height: 60rpx;
		border: 1px solid #eee;
		border-radius: 10rpx;
		padding: 0 20rpx;
		font-size: 28rpx;
	}

	/* 快捷充值 */
	.quick-recharge-box {
		margin-bottom: 30rpx;
	}

	.quick-recharge-label {
		font-size: 30rpx;
		color: #333;
		display: block;
		margin-bottom: 10rpx;
	}

	.quick-amount-list {
		display: flex;
		flex-wrap: wrap;
		gap: 20rpx;
		justify-content: space-around;
	}

	.quick-amount-item {
		width: 24%;
		background-color: #fff;
		border: 1px solid #eee;
		border-radius: 10rpx;
		padding: 15rpx;
		text-align: center;
		font-size: 26rpx;
	}

	.quick-amount-item.active {
		border-color: #4b8df8;
		color: #4b8df8;
	}

	.amount-value {
		font-weight: bold;
		display: block;
	}

	.original-price {
		font-size: 22rpx;
		color: #999;
	}

	/* 协议与按钮 */
	.agreement-box {
		display: flex;
		align-items: center;
		margin-bottom: 15rpx;
		font-size: 24rpx;
		color: #666;
	}

	.agreement-checkbox {
		margin-right: 10rpx;
		transform: scale(0.8);
	}

	.confirm-recharge-btn {
		width: 100%;
		background: linear-gradient(to right, #4284ff, #545ce9);
		color: #fff;
		font-size: 32rpx;
		border-radius: 10rpx;
		padding: 20rpx 0;
		margin-bottom: 15rpx;
	}

	/* 充值协议链接样式 */
	.policy-link-text {
		color: #4b8df8;
		text-decoration: underline;
		margin-left: 5rpx;
	}

	/* 充值协议弹窗样式 */
	.recharge-policy-popup {
		position: fixed;
		top: 0;
		left: 0;
		width: 100%;
		height: 100%;
		z-index: 1000;
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.popup-mask {
		position: absolute;
		top: 0;
		left: 0;
		width: 100%;
		height: 100%;
		background-color: rgba(0, 0, 0, 0.5);
	}

	.popup-content {
		position: relative;
		background-color: #fff;
		border-radius: 20rpx;
		width: 90%;
		max-width: 750rpx;
		overflow: hidden;
	}

	.popup-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 30rpx 20rpx;
		background-color: #f5f7fa;
		border-bottom: 1rpx solid #eee;
	}

	.popup-title {
		font-size: 32rpx;
		font-weight: bold;
		color: #333;
	}

	.close-btn {
		font-size: 36rpx;
		color: #999;
	}

	.policy-content {
		padding: 30rpx;
		max-height: 600rpx;
		overflow-y: auto;
	}

	.policy-title {
		font-size: 28rpx;
		font-weight: bold;
		color: #333;
		margin: 20rpx 0 10rpx;
	}

	.policy-paragraph {
		font-size: 24rpx;
		color: #666;
		line-height: 1.6;
		margin-bottom: 15rpx;
		text-align: justify;
	}

	.popup-footer {
		display: flex;
		padding: 20rpx 30rpx;
		border-top: 1rpx solid #eee;
	}

	.reject-btn,
	.accept-btn {
		flex: 1;
		height: 80rpx;
		line-height: 80rpx;
		border-radius: 10rpx;
		margin: 0 10rpx;
		font-size: 28rpx;
	}

	.reject-btn {
		background-color: #f5f5f5;
		color: #666;
	}

	.accept-btn {
		background: linear-gradient(to right, #4284ff, #545ce9);
		color: #fff;
	}
</style>